﻿using Azure.Storage.Blobs;
using Core.FrameWork.Commons.Hepler;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Core.FrameWork.Commons.Storage.Azure
{
    public static class AzureStorageExtensions
    {

        public static async Task<string> Save(this byte[] fileData, string fileName, BlobFileType fileType = BlobFileType.Image)
        {
            fileName = $"{fileType}/{fileName}";
            return await UploadFile(fileData, fileName, fileType);
        }

        public static string BitmapSave(this Bitmap img, string fileName, out byte[] qrbyte, BlobFileType fileType = BlobFileType.Image)
        {
            qrbyte = Bitmap2Byte(img);
            fileName = $"{fileType}/{fileName}";
            return UploadFile(qrbyte, fileName, fileType).Result;
        }

        private static async Task<string> UploadFile(byte[] fileData, string fileName, BlobFileType fileType = BlobFileType.Image)
        {
            //BlobContainerClient container = BlobService.CreateBlobContainer(AzureConfig.BlobContainers[fileType]);

            var container = new BlobContainerClient(AzureConfig.AzureBlobConfig.ToString(), AzureConfig.BlobContainers[fileType]);
            try
            {
                Stream stream = new MemoryStream(fileData);
                await container.UploadBlobAsync($"{fileName}", stream);
                return $"{container.Uri}/{fileName}";
            }
            catch (Exception ex)
            {
                return "";
            }
        }

        public static async Task<string> Save(this Image img, string fileName, ImageFormat imageFormat, BlobFileType fileType = BlobFileType.Image)
        {
            var fileData = Bitmap2Byte(img);
            fileName = $"{fileType}/{fileName}";
            return await UploadFile(fileData, fileName, fileType);
        }
        public static async Task<string> AzureSave(this Bitmap img, string fileName, ImageFormat imageFormat, BlobFileType fileType = BlobFileType.Image)
        {
            var fileData = Bitmap2Byte(img);
            fileName = $"{fileType}/{fileName}";
            return await UploadFile(fileData, fileName, fileType);
        }
        public static byte[] Bitmap2Byte(Image bitmap)
        {
            using MemoryStream stream = new MemoryStream();
            bitmap.Save(stream, ImageFormat.Jpeg);
            byte[] data = new byte[stream.Length];
            stream.Seek(0, SeekOrigin.Begin);
            stream.Read(data, 0, Convert.ToInt32(stream.Length));
            return data;
        }
    }
}
